home *** CD-ROM | disk | FTP | other *** search
/ HyperLib 1997 Winter - Disc 1 / HYPERLIB-1997-Winter-CD1.ISO.7z / HYPERLIB-1997-Winter-CD1.ISO / オンラインウェア / PRG / MacPerl 506 appl folder.sit / MacPerl 506 appl folder / Mac_Perl_506r1m_appl / lib / Math / BigInt.pm < prev    next >
Text File  |  1994-12-26  |  10KB  |  348 lines

  1. package Math::BigInt;
  2.  
  3. %OVERLOAD = ( 
  4.                 # Anonymous subroutines:
  5. '+'    =>    sub {new BigInt &badd},
  6. '-'    =>    sub {new BigInt
  7.                $_[2]? bsub($_[1],${$_[0]}) : bsub(${$_[0]},$_[1])},
  8. '<=>'    =>    sub {new BigInt
  9.                $_[2]? bcmp($_[1],${$_[0]}) : bcmp(${$_[0]},$_[1])},
  10. 'cmp'    =>    sub {new BigInt
  11.                $_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
  12. '*'    =>    sub {new BigInt &bmul},
  13. '/'    =>    sub {new BigInt 
  14.                $_[2]? scalar bdiv($_[1],${$_[0]}) :
  15.              scalar bdiv(${$_[0]},$_[1])},
  16. '%'    =>    sub {new BigInt
  17.                $_[2]? bmod($_[1],${$_[0]}) : bmod(${$_[0]},$_[1])},
  18. '**'    =>    sub {new BigInt
  19.                $_[2]? bpow($_[1],${$_[0]}) : bpow(${$_[0]},$_[1])},
  20. 'neg'    =>    sub {new BigInt &bneg},
  21. 'abs'    =>    sub {new BigInt &babs},
  22.  
  23. qw(
  24. ""    stringify
  25. 0+    numify)            # Order of arguments unsignificant
  26. );
  27.  
  28. sub new {
  29.   my $foo = bnorm($_[1]);
  30.   die "Not a number initialized to BigInt" if $foo eq "NaN";
  31.   bless ¥$foo;
  32. }
  33. sub stringify { "${$_[0]}" }
  34. sub numify { 0 + "${$_[0]}" }    # Not needed, additional overhead
  35.                 # comparing to direct compilation based on
  36.                 # stringify
  37.  
  38. # arbitrary size integer math package
  39. #
  40. # by Mark Biggar
  41. #
  42. # Canonical Big integer value are strings of the form
  43. #       /^[+-]¥d+$/ with leading zeros suppressed
  44. # Input values to these routines may be strings of the form
  45. #       /^¥s*[+-]?[¥d¥s]+$/.
  46. # Examples:
  47. #   '+0'                            canonical zero value
  48. #   '   -123 123 123'               canonical value '-123123123'
  49. #   '1 23 456 7890'                 canonical value '+1234567890'
  50. # Output values always always in canonical form
  51. #
  52. # Actual math is done in an internal format consisting of an array
  53. #   whose first element is the sign (/^[+-]$/) and whose remaining 
  54. #   elements are base 100000 digits with the least significant digit first.
  55. # The string 'NaN' is used to represent the result when input arguments 
  56. #   are not numbers, as well as the result of dividing by zero
  57. #
  58. # routines provided are:
  59. #
  60. #   bneg(BINT) return BINT              negation
  61. #   babs(BINT) return BINT              absolute value
  62. #   bcmp(BINT,BINT) return CODE         compare numbers (undef,<0,=0,>0)
  63. #   badd(BINT,BINT) return BINT         addition
  64. #   bsub(BINT,BINT) return BINT         subtraction
  65. #   bmul(BINT,BINT) return BINT         multiplication
  66. #   bdiv(BINT,BINT) return (BINT,BINT)  division (quo,rem) just quo if scalar
  67. #   bmod(BINT,BINT) return BINT         modulus
  68. #   bgcd(BINT,BINT) return BINT         greatest common divisor
  69. #   bnorm(BINT) return BINT             normalization
  70. #
  71.  
  72. $zero = 0;
  73.  
  74. # normalize string form of number.   Strip leading zeros.  Strip any
  75. #   white space and add a sign, if missing.
  76. # Strings that are not numbers result the value 'NaN'.
  77.  
  78. sub bnorm { #(num_str) return num_str
  79.     local($_) = @_;
  80.     s/¥s+//g;                           # strip white space
  81.     if (s/^([+-]?)0*(¥d+)$/$1$2/) {     # test if number
  82.     substr($_,$[,0) = '+' unless $1; # Add missing sign
  83.     s/^-0/+0/;
  84.     $_;
  85.     } else {
  86.     'NaN';
  87.     }
  88. }
  89.  
  90. # Convert a number from string format to internal base 100000 format.
  91. #   Assumes normalized value as input.
  92. sub internal { #(num_str) return int_num_array
  93.     local($d) = @_;
  94.     ($is,$il) = (substr($d,$[,1),length($d)-2);
  95.     substr($d,$[,1) = '';
  96.     ($is, reverse(unpack("a" . ($il%5+1) . ("a5" x ($il/5)), $d)));
  97. }
  98.  
  99. # Convert a number from internal base 100000 format to string format.
  100. #   This routine scribbles all over input array.
  101. sub external { #(int_num_array) return num_str
  102.     $es = shift;
  103.     grep($_ > 9999 || ($_ = substr('0000'.$_,-5)), @_);   # zero pad
  104.     &bnorm(join('', $es, reverse(@_)));    # reverse concat and normalize
  105. }
  106.  
  107. # Negate input value.
  108. sub bneg { #(num_str) return num_str
  109.     local($_) = &bnorm(@_);
  110.     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0';
  111.     s/^H/N/;
  112.     $_;
  113. }
  114.  
  115. # Returns the absolute value of the input.
  116. sub babs { #(num_str) return num_str
  117.     &abs(&bnorm(@_));
  118. }
  119.  
  120. sub abs { # post-normalized abs for internal use
  121.     local($_) = @_;
  122.     s/^-/+/;
  123.     $_;
  124. }
  125. # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
  126. sub bcmp { #(num_str, num_str) return cond_code
  127.     local($x,$y) = (&bnorm($_[$[]),&bnorm($_[$[+1]));
  128.     if ($x eq 'NaN') {
  129.     undef;
  130.     } elsif ($y eq 'NaN') {
  131.     undef;
  132.     } else {
  133.     &cmp($x,$y);
  134.     }
  135. }
  136.  
  137. sub cmp { # post-normalized compare for internal use
  138.     local($cx, $cy) = @_;
  139.     $cx cmp $cy
  140.     &&
  141.     (
  142.     ord($cy) <=> ord($cx)
  143.     ||
  144.     ($cx cmp ',') * (length($cy) <=> length($cx) || $cy cmp $cx)
  145.     );
  146. }
  147.  
  148. sub badd { #(num_str, num_str) return num_str
  149.     local(*x, *y); ($x, $y) = (&bnorm($_[$[]),&bnorm($_[$[+1]));
  150.     if ($x eq 'NaN') {
  151.     'NaN';
  152.     } elsif ($y eq 'NaN') {
  153.     'NaN';
  154.     } else {
  155.     @x = &internal($x);             # convert to internal form
  156.     @y = &internal($y);
  157.     local($sx, $sy) = (shift @x, shift @y); # get signs
  158.     if ($sx eq $sy) {
  159.         &external($sx, &add(*x, *y)); # if same sign add
  160.     } else {
  161.         ($x, $y) = (&abs($x),&abs($y)); # make abs
  162.         if (&cmp($y,$x) > 0) {
  163.         &external($sy, &sub(*y, *x));
  164.         } else {
  165.         &external($sx, &sub(*x, *y));
  166.         }
  167.     }
  168.     }
  169. }
  170.  
  171. sub bsub { #(num_str, num_str) return num_str
  172.     &badd($_[$[],&bneg($_[$[+1]));    
  173. }
  174.  
  175. # GCD -- Euclids algorithm Knuth Vol 2 pg 296
  176. sub bgcd { #(num_str, num_str) return num_str
  177.     local($x,$y) = (&bnorm($_[$[]),&bnorm($_[$[+1]));
  178.     if ($x eq 'NaN' || $y eq 'NaN') {
  179.     'NaN';
  180.     } else {
  181.     ($x, $y) = ($y,&bmod($x,$y)) while $y ne '+0';
  182.     $x;
  183.     }
  184. }
  185. # routine to add two base 1e5 numbers
  186. #   stolen from Knuth Vol 2 Algorithm A pg 231
  187. #   there are separate routines to add and sub as per Kunth pg 233
  188. sub add { #(int_num_array, int_num_array) return int_num_array
  189.     local(*x, *y) = @_;
  190.     $car = 0;
  191.     for $x (@x) {
  192.     last unless @y || $car;
  193.     $x -= 1e5 if $car = (($x += shift(@y) + $car) >= 1e5);
  194.     }
  195.     for $y (@y) {
  196.     last unless $car;
  197.     $y -= 1e5 if $car = (($y += $car) >= 1e5);
  198.     }
  199.     (@x, @y, $car);
  200. }
  201.  
  202. # subtract base 1e5 numbers -- stolen from Knuth Vol 2 pg 232, $x > $y
  203. sub sub { #(int_num_array, int_num_array) return int_num_array
  204.     local(*sx, *sy) = @_;
  205.     $bar = 0;
  206.     for $sx (@sx) {
  207.     last unless @y || $bar;
  208.     $sx += 1e5 if $bar = (($sx -= shift(@sy) + $bar) < 0);
  209.     }
  210.     @sx;
  211. }
  212.  
  213. # multiply two numbers -- stolen from Knuth Vol 2 pg 233
  214. sub bmul { #(num_str, num_str) return num_str
  215.     local(*x, *y); ($x, $y) = (&bnorm($_[$[]), &bnorm($_[$[+1]));
  216.     if ($x eq 'NaN') {
  217.     'NaN';
  218.     } elsif ($y eq 'NaN') {
  219.     'NaN';
  220.     } else {
  221.     @x = &internal($x);
  222.     @y = &internal($y);
  223.     &external(&mul(*x,*y));
  224.     }
  225. }
  226.  
  227. # multiply two numbers in internal representation
  228. # destroys the arguments, supposes that two arguments are different
  229. sub mul { #(*int_num_array, *int_num_array) return int_num_array
  230.     local(*x, *y) = (shift, shift);
  231.     local($signr) = (shift @x ne shift @y) ? '-' : '+';
  232.     @prod = ();
  233.     for $x (@x) {
  234.       ($car, $cty) = (0, $[);
  235.       for $y (@y) {
  236.     $prod = $x * $y + $prod[$cty] + $car;
  237.     $prod[$cty++] =
  238.       $prod - ($car = int($prod * 1e-5)) * 1e5;
  239.       }
  240.       $prod[$cty] += $car if $car;
  241.       $x = shift @prod;
  242.     }
  243.     ($signr, @x, @prod);
  244. }
  245.  
  246. # modulus
  247. sub bmod { #(num_str, num_str) return num_str
  248.     (&bdiv(@_))[$[+1];
  249. }
  250. sub bdiv { #(dividend: num_str, divisor: num_str) return num_str
  251.     local (*x, *y); ($x, $y) = (&bnorm($_[$[]), &bnorm($_[$[+1]));
  252.     return wantarray ? ('NaN','NaN') : 'NaN'
  253.     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0');
  254.     return wantarray ? ('+0',$x) : '+0' if (&cmp(&abs($x),&abs($y)) < 0);
  255.     @x = &internal($x); @y = &internal($y);
  256.     $srem = $y[$[];
  257.     $sr = (shift @x ne shift @y) ? '-' : '+';
  258.     $car = $bar = $prd = 0;
  259.     if (($dd = int(1e5/($y[$#y]+1))) != 1) {
  260.     for $x (@x) {
  261.         $x = $x * $dd + $car;
  262.         $x -= ($car = int($x * 1e-5)) * 1e5;
  263.     }
  264.     push(@x, $car); $car = 0;
  265.     for $y (@y) {
  266.         $y = $y * $dd + $car;
  267.         $y -= ($car = int($y * 1e-5)) * 1e5;
  268.     }
  269.     }
  270.     else {
  271.     push(@x, 0);
  272.     }
  273.     @q = (); ($v2,$v1) = @y[-2,-1];
  274.     while ($#x > $#y) {
  275.     ($u2,$u1,$u0) = @x[-3..-1];
  276.     $q = (($u0 == $v1) ? 99999 : int(($u0*1e5+$u1)/$v1));
  277.     --$q while ($v2*$q > ($u0*1e5+$u1-$q*$v1)*1e5+$u2);
  278.     if ($q) {
  279.         ($car, $bar) = (0,0);
  280.         for ($y = $[, $x = $#x-$#y+$[-1; $y <= $#y; ++$y,++$x) {
  281.         $prd = $q * $y[$y] + $car;
  282.         $prd -= ($car = int($prd * 1e-5)) * 1e5;
  283.         $x[$x] += 1e5 if ($bar = (($x[$x] -= $prd + $bar) < 0));
  284.         }
  285.         if ($x[$#x] < $car + $bar) {
  286.         $car = 0; --$q;
  287.         for ($y = $[, $x = $#x-$#y+$[-1; $y <= $#y; ++$y,++$x) {
  288.             $x[$x] -= 1e5
  289.             if ($car = (($x[$x] += $y[$y] + $car) > 1e5));
  290.         }
  291.         }   
  292.     }
  293.     pop(@x); unshift(@q, $q);
  294.     }
  295.     if (wantarray) {
  296.     @d = ();
  297.     if ($dd != 1) {
  298.         $car = 0;
  299.         for $x (reverse @x) {
  300.         $prd = $car * 1e5 + $x;
  301.         $car = $prd - ($tmp = int($prd / $dd)) * $dd;
  302.         unshift(@d, $tmp);
  303.         }
  304.     }
  305.     else {
  306.         @d = @x;
  307.     }
  308.     (&external($sr, @q), &external($srem, @d, $zero));
  309.     } else {
  310.     &external($sr, @q);
  311.     }
  312. }
  313.  
  314. # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
  315. sub bpow { #(num_str, num_str) return num_str
  316.     local(*x, *y); ($x, $y) = (&bnorm($_[$[]), &bnorm($_[$[+1]));
  317.     if ($x eq 'NaN') {
  318.     'NaN';
  319.     } elsif ($y eq 'NaN') {
  320.     'NaN';
  321.     } elsif ($x eq '+1') {
  322.     '+1';
  323.     } elsif ($x eq '-1') {
  324.     &bmod($x,2) ? '-1': '+1';
  325.     } elsif ($y =~ /^-/) {
  326.     'NaN';
  327.     } elsif ($x eq '+0' && $y eq '+0') {
  328.     'NaN';
  329.     } else {
  330.     @x = &internal($x);
  331.     local(@pow2)=@x;
  332.     local(@pow)=&internal("+1");
  333.     local($y1,$res,@tmp1,@tmp2)=(1); # need tmp to send to mul
  334.     while ($y ne '+0') {
  335.       ($y,$res)=&bdiv($y,2);
  336.       if ($res ne '+0') {@tmp=@pow2; @pow=&mul(*pow,*tmp);}
  337.       if ($y ne '+0') {@tmp=@pow2;@pow2=&mul(*pow2,*tmp);}
  338.     }
  339.     &external(@pow);
  340.     }
  341. }
  342.  
  343. 1;
  344.